const fs = require("fs");
const express = require("express");
const httpProxy = require("http-proxy");
const path = require("path");
const devConfig = require("../build/webpack.dev");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const proxySettings = require("./settings");

const mockDataRootPath = path.posix.join(__dirname, "mock-data");
const rootPath = path.resolve(__dirname, "..");

const getMockDataInfo = (url) => {
  let pathArr = url.split("/");
  const apiMapping = require(`./mock-data/${pathArr[0]}/api`);
  let key = url.replace(`${pathArr[0]}/api`, '');
  const mappingObj = apiMapping[key];
  console.log(key, mappingObj);
  if (mappingObj) {
    let fullPath = "";
    if (["common-resp", "err-resp"].includes(mappingObj.filename)) {
      fullPath = path.posix.join(mockDataRootPath, mappingObj.filename + ".json");
    } else {
      fullPath = path.posix.join(mockDataRootPath, pathArr[0], pathArr[2], mappingObj.filename + ".json");
    }
    console.log(fullPath);
    return {
      path: fullPath,
      status: mappingObj.status,
    };
  } else {
    return {
      path: path.posix.join(mockDataRootPath, "empty.json"),
      status: 200,
    };
  }
};

let isMock = false;
if (process.argv.length === 3 && process.argv[2] === "mock") {
  isMock = true;
}

const app = express();
const proxy = httpProxy.createProxyServer({
  target: {
    host: proxySettings.backend.host,
    port: proxySettings.backend.port,
  },
});

proxy.on("error", (err, req, res) => {
  res.status(500).json({
    message: err.message,
  });
});

const port = proxySettings.frontend.port;
const compiler = webpack(devConfig);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: devConfig.output.publicPath,
  })
);

app.use(webpackHotMiddleware(compiler));

app.post("/**", (req, res) => {
  if (isMock) {
    const api = req.url.replace(/\?.*$/, "").replace("/", "");
    console.log(api);
    const dataInfo = getMockDataInfo(api);
    const data = fs.readFileSync(dataInfo.path);
    res.status(dataInfo.status).json(JSON.parse(data));
  } else {
    return proxy.web(req, res);
  }
});

app.use("/", (req, res) => {
  res.sendFile(rootPath + "/public/index.html");
});

app.use(express.static(rootPath + "/public/"));

app.listen(port, (error) => {
  if (error) {
    throw error;
  } else {
    console.info("Listening on port %s.", port);
  }
});
